<?php

namespace App\Http\Controllers\LibApi;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 自有资源
 */
class CdbtResourceController
{
    private static $appid = 'resource_manage_external';
    private static $access_id = 'yzqlib';
    private static $appsecret = 'eb48162e87094efae2a05dd329f2ee27';

    // private static $serviceAddr = 'https://draw.huilanyun.com'; //本地测试服务器地址
    private static $serviceAddr = ''; //本地测试服务器地址

    private static $getToken = '/getExternalToken'; //获取token
    private static $getResourceList = '/external/index/getResourceList'; //获取资源数据
    private static $getDownResourceId = '/external/index/getDownResourceId'; //获取所有下架资源id

    private static $getResourceChapter = '/external/index/getResourceChapter'; //获取资源章节信息（视频集数，音频集数）
    private static $getEbookUrl = '/external/index/getEbookUrl'; //根据电子书资源id获取电子书阅读资源地址
    private static $getAudioUrl = '/external/index/getAudioUrl'; //根据音频资源id获取音频资源地址
    private static $getVideoUrl = '/external/index/getVideoUrl'; //根据视频资源id获取视频资源地址

    public function __construct()
    {
        $localhost_name = ['admin-PC', 'DESKTOP-7IDE35R']; //本地主机地址，用于切换不同的地址
        if (!in_array(gethostname(), $localhost_name)) {
            //正式环境
            self::$serviceAddr = 'https://book.usharego.com/resource_manage/public';
        } else {
            //其他情况，走本地测试环境
            self::$serviceAddr = 'http://192.168.1.12/resource_manage/public';
        }
    }

    /**
     * 获取  access_token （已对接）
     */
    public function getAccessToken()
    {
        $url = self::$serviceAddr . self::$getToken;
        $timestamp = time() . '000';
        $code = strtoupper(md5(self::$appid . self::$appsecret . $timestamp));
        $access_token_param = array(
            'timestamp'    => $timestamp,
            'code' => $code,
        );
        $access_token_param = http_build_query($access_token_param);
        $result = $this->requestCurl($url . '?' . $access_token_param, $access_token_param); //必须post请求，但是参数需要像get那样拼接
        $results = json_decode($result, true); //json字符串转为数组
        if (empty($results) || $results['code'] != 200) exit(json_encode(['code' => 202, 'msg' => 'access_token获取失败']));
        $access_token = $results['content']['token'];
        $expires_in = $results['content']['expires_in'];
        //储存access_token
        Cache::put("resource_manage_token", $access_token, $expires_in); //缓存3600秒

        return $access_token;
    }

    /**
     * 获取资源数据
     * big_type_id id  系统大类 1 电子书  2 有声书（音频） 3 视频   不可为空
     */
    public function getResourceList($big_type_id, $page = 1, $limit = 10)
    {
        if (empty($big_type_id)) {
            return ['code' => 201, 'msg' => '参数错误'];
        }
        $url = self::$serviceAddr . self::$getResourceList;

        $param = [
            'access_id'  => self::$access_id,
            'big_type_id'  => $big_type_id,
            'page' => $page,
            'limit' => $limit,
        ];
        $param = json_encode($param);

        $access_token = Cache::get('resource_manage_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }
        $result = $this->requestCurl($url, $param, $access_token, true); //然后重新请求
        $results = json_decode($result, true); //json字符串转为数组
        if ($results['code'] === 200) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['content']];
        }
        return ['code' => $results['code'], 'msg' => $results['msg']];
    }


    /**
     * 获取资源数据
     * big_type_id id  系统大类 1 电子书  2 有声书（音频） 3 视频   可为空
     */
    public function getDownResourceId($page = 1, $limit = 10)
    {
        $url = self::$serviceAddr . self::$getDownResourceId;

        $param = [
            'access_id'  => self::$access_id,
            'page' => $page,
            'limit' => $limit,
        ];
        $param = json_encode($param);

        $access_token = Cache::get('resource_manage_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }
        $result = $this->requestCurl($url, $param, $access_token, true); //然后重新请求
        $results = json_decode($result, true); //json字符串转为数组
        if ($results['code'] === 200) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['content']];
        }
        return ['code' => $results['code'], 'msg' => $results['msg']];
    }



    /**
     * 获取资源章节数据（电子书、视频、视频章节）
     * data_unique_id id  资源唯一id
     */
    public function getResourceChapter($data_unique_id)
    {
        $url = self::$serviceAddr . self::$getResourceChapter;
        $param = [
            'access_id'  => self::$access_id,
            'guid' => $data_unique_id,
        ];
        $param = json_encode($param);

        $access_token = Cache::get('resource_manage_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }
        $result = $this->requestCurl($url, $param, $access_token, true); //然后重新请求
        $results = json_decode($result, true); //json字符串转为数组
        if ($results['code'] === 200) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['content']];
        }
        return ['code' => $results['code'], 'msg' => $results['msg']];
    }

    /**
     * 根据电子书资源id获取电子书阅读资源地址
     * data_unique_id id  资源唯一id
     */
    public function getEbookSkipAddress($data_unique_id)
    {
        $url = self::$serviceAddr . self::$getEbookUrl;
        $param = [
            'access_id'  => self::$access_id,
            'guid' => $data_unique_id,
        ];
        $param = json_encode($param);

        $access_token = Cache::get('resource_manage_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }
        $result = $this->requestCurl($url, $param, $access_token, true); //然后重新请求
        $results = json_decode($result, true); //json字符串转为数组
        if ($results['code'] === 200) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['content']];
        }
        return ['code' => $results['code'], 'msg' => $results['msg']];
    }



    /**
     * @param $url
     * @param null $params
     * @param bool $json  json  格式数据    Content-Type  需要修改  成 application/json
     * @return mixed
     */
    private  static  function requestCurl($url, $params = null, $access_token = null, $json = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if (!empty($params)) {
            if (is_array($params)) {
                //如果传的是数组，就要进行对参数进行 &拼接
                $params = http_build_query($params);
            }
            if ($json) {
                curl_setopt(
                    $ch,
                    CURLOPT_HTTPHEADER,
                    array(
                        'Authorization: Bearer ' . $access_token,
                        'Content-Type: application/json',
                        'Content-Length: ' . strlen($params)
                    )
                );
            }
            // curl_setopt($ch, CURLOPT_POST, 1);
            // curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        //都是用post格式
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        $body = curl_exec($ch);
        // dump(curl_error($ch));
        curl_close($ch);
        return $body;
    }
}
